﻿using AnlianCommon.Common.Domains.ProductionManagement;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;

namespace SheepCommon.API.SheepCommands.EChartsCommon
{
    public class SheepRecordBreedTypeQueryHandler : IRequestHandler<SheepRecordBreedTypeQueryCommand, Result>
    {
        private readonly IBaseRepository<SheepArchives> _sheepArchivesRepository;

        public SheepRecordBreedTypeQueryHandler(IBaseRepository<SheepArchives> sheepArchivesRepository)
        {
            _sheepArchivesRepository = sheepArchivesRepository;
        }
        /// <summary>
        /// 种公品种统计
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SheepRecordBreedTypeQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            try
            {
                var sheepRecordBreedType = await (from a in await _sheepArchivesRepository.GetAll()
                                                  select new SheepRecordBreedTypeDto()
                                                  {
                                                      //RecordType = a.RecordType,
                                                      name = a.RecordBreed,
                                                  }).ToListAsync();
                if(request.RecordType!=-1)
                {
                    sheepRecordBreedType = sheepRecordBreedType.Where(c=>c.RecordType == request.RecordType).ToList();
                }
                sheepRecordBreedType = await (from a in await _sheepArchivesRepository.GetAll()
                                              where a.RecordType == request.RecordType
                                              group a by a.RecordBreed into a
                                              select new SheepRecordBreedTypeDto()
                                              {
                                                  value = a.Count(),
                                                  name = a.Key,
                                              }).ToListAsync();
                result.Data = sheepRecordBreedType;
                
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
